<template>
	<view class="order-page">
		<tabBar selectedIndex=2></tabBar>
		<view class="search-con c-flex c-flex-col">
			<!-- <view class="c-flex jc-between gap-5">
				<view class="input-con c-flex jc-start c-item-center ">
					<image :src="remoteImgUrl+'search-icon.png'"
						style="width: 42rpx;max-height: 42rpx;    margin-right: 12rpx;"></image>
					<input class="uni-input" v-model="lpgUserName" name="text" style="width:72%" confirm-type="search"
						placeholder="根据订单名称搜索" @input="onInputChange" />
					<view class="line"></view>
					<text @click="onInputChange">搜索</text>
				</view>
			</view> -->
		</view>
		<view class="tabs-con c-flex c-flex-row jc-between">
			<view class="tab-item" v-for="(item,index) in tabbarArr" :key="index" @click="onTabbarClick(item)"
				:class="{'selected':item.selected}">
				<image class="sele-bg" v-if="item.selected" :src="orderImgUrl+'choose.png'"></image>
				{{item.label}}
			</view>
		</view>
		<!-- 列表 -->
		<mescroll-body ref="mescrollRef" @init="mescrollInit" :down="downOption" @down="downCallback" :up="upOption"
			@up="upCallback">
			<view class="p-list">
				<view class="p-l-item" v-for="(item,i) in list" :key="i" @tap='orderDetail(item)'>
					<view class="title-con c-flex jc-between c-item-center">
						<text>{{item.createTime}}</text>
						<text
							:class="item.status ===5|| item.status ===4?'order_stauts_complete':''">{{ordeStatusText(item.status)}}</text>

					</view>
					<view class="p-content">
						<view class="p-c-item c-flex jc-between" v-for="(good,g) in item.items" :key="g">
							<view class="goodInfo c-flex c-item-center">
								<view class="goodImg c-flex c-item-center jc-center">
									<image :src="good.pic"></image>
								</view>
								<view class="standards">
									<view>{{good.name}}</view>

									<view>
										单价￥{{good.price}}
									</view>
									<view>数量：x{{good.saleCount}}</view>
								</view>
							</view>

							<view class="saleAmount">
								￥{{good.saleAmount}}
							</view>

						</view>
					</view>


					<view class="p-price  c-flex jc-end">

						<view class="payAmount">
							<text>{{sliceGood(item.items)}}</text>
							<text v-if="item.status===0" style="margin-left: 10rpx;">应付金额：</text>
							<text v-if="item.status!==0" style="margin-left: 10rpx;">实付金额：</text>
							<text class="txt_0">￥{{item.payAmount}}</text>
							<text class="txt_1">(含配送费￥{{item.freightAmount}})</text>
						</view>
					</view>
					<view class="p-btn c-flex jc-end">
						<view v-if="item.status===0  || item.status===1" class="contactBtn" @tap.stop="btnHandler(item,'cancel')">取消订单</view>
						<view v-if="item.status===0 && item.countdown" class="payBtn" @tap.stop="btnHandler(item,'pay')">去支付 {{item.countdown}}
						</view>
						<!-- <view v-if="item.status===5" class="contactBtn" @tap="btnHandler(item,'del')">删除订单</view> -->
					</view>
					<view class="p-btn c-flex jc-end" v-if="item.status===2">
						<view class="contactBtn" @tap.stop="btnHandler(item,'call')">致电骑手</view>

					</view>
				</view>
			</view>
		</mescroll-body>
		<tydPrompt ref='tydPrompt' :content="content" @confirmPrompt='confirmPrompt'></tydPrompt>

	</view>
</template>

<script>
	import {
		maskPhoneNumber,toast,debounce
	} from '@/utils/utils.js'
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
	import {
		USER_OREDR_STATUS
	} from '@/utils/global.js';
	import tydPrompt from '@/components/tyd-prompt/tyd-prompt.vue';
	import {
		mapStatus,
		mapMutations
	} from 'vuex'
	export default {
		components: {
			tydPrompt
		},
		mixins: [MescrollMixin], // 使用mixin (在main.js注册全局组件，内部已注册onPullDownRefresh)
		data() {
			return {
				content: '确定取消当前订单？',
				remoteImgUrl: this.$API.IMG_URL + '/construct-supervision-mp/',
				orderImgUrl: this.$API.IMG_URL + '/gas/yehuaqi/order/',
				lpgUserName: '',
				tabbarItem: null,
				tabbarArr: [],
				downOption: {
					auto:false,
					native: true // 必须配置此项，且需在pages.json配置"enablePullDownRefresh" : true
				},
				upOption: {
					auto:true,
					noMoreSize: 4,
					empty: {
						tip: '~ 您还没有订单哦 ~',
						btnText: ''
					}
				},
				page: 1,
				limit: 10,
				indicatorStyle: `height: 50px;line-height:50px;`,
				list: [],
				orderId: null,
				orderStatus: '',
				orderCountdown: 30,
				allClearTimer: [],
				orderItem:null
			};
		},
		computed: {
			// remainingTime() {
			// 	const minutes = Math.floor(this.totalTime / 60);
			// 	const seconds = this.totalTime % 60;
			// 	return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
			// },
		},
		
		onHide() {
			console.log('onHide')
			this.allClearTimer.forEach(item => {
				this.$timerManager.clearTimer(item.name);
			})
		},
		onLoad(options) {
			console.log('onLoad')
			uni.setNavigationBarColor({
				backgroundColor: '#f9ead5',
				frontColor: '#000000'
			});
			this.tabbarArr = USER_OREDR_STATUS;

		},
		onShow() {
			console.log('onShow')

			this.initTabbar();

		},
		methods: {
			...mapMutations(['setUserOrderStatus', 'setPageBackDelta']),
			sliceGood(arr) {
				let newArr = JSON.parse(JSON.stringify(arr));
				
			
				let num=0;
				
				newArr.map(item => {
					
				
					num +=item.saleCount
				})
			
			
				return '共'+num+'件商品';
			},
			orderDetail(item){
				uni.navigateTo({
					url:'/pages/client/detailOrder/detailOrder?item='+JSON.stringify(item)
				})
			},
			initTabbar() {

				this.tabbarArr.forEach(item => {
					item['selected'] = false;
				});
				this.tabbarItem = this.$store.getters.userOrderStatus;
				//this.tabbarItem = USER_OREDR_STATUS[0];
				
				this.tabbarItem.selected = true;
				if (this.tabbarItem.value === 2) {
					this.orderStatus = '1,2,3'
				}
				this.initData();
			},
			ordeStatusText(status) {
				switch (status) {
					case 0:
						return '待支付'
					case 1:
						return '待接单'
					case 2:
						return '待送达'
					case 3:
						return '待安检'
					case 4:
						return '已安检'
					case 5:
						return '已取消'
					case 6:
						return '退款中'
				}
			},
			btnHandler:debounce(function(item, btnStr){
				switch (btnStr) {
					case 'pay':
						this.goPay(item);
						break;
					case 'call':
						this.callPhone(item.staffPhone)
						break;
					case 'del':
						this.delOrder(item);
						break;
					case 'cancel':
						this.orderItem = item;
						
						this.$refs.tydPrompt.open();
					
						break;
				}
			},500),
			
			goPay(item) {
				this.$API.payOrder({
					id: item.id
				}).then(res => {
					if (res.code === 0) {
				
						//this.setOrderStatus(USER_OREDR_STATUS[1]);
						//this.initTabbar();
						this.wxPay(res.prepayInfo,item)
						
				
					}
				}).catch(() => {
				
				});
			},
			wxPay(res,item) {
				let that = this;
				wx.requestPayment({
					provider: "wxpay",
					timeStamp: String(res.timeStamp),
					nonceStr: String(res.nonceStr),
					package: String(res.packageValue),
					signType: String(res.signType),
					paySign: String(res.paySign),
					appId: res.appId,
					success(res) {
						console.log(res)
						toast("支付成功");
						that.$timerManager.clearTimer('orderCancelTimer'+item.id);
						that.initData();
						
					},
					fail(res) {
						console.log(res)
						//that.initData();
						toast(res);
					}
				})
			},
			delOrder(item) {},
			cancelOrder() {
				this.$API.cancelOrder({
					id:  this.orderItem.id
				}).then(res => {
					if (res.code === 0) {
						if(this.orderItem.status ===0){
							this.$timerManager.clearTimer('orderCancelTimer'+this.orderItem.id);
						}
						this.initData();
				
					}
				}).catch(() => {
				
				});
			},
			confirmPrompt() {
				this.cancelOrder();
			},
			
			callPhone(phoneNumber) {
				uni.makePhoneCall({
					phoneNumber: phoneNumber, // 电话号码
					success: function() {
						console.log('拨打电话成功');
					},
					fail: function(err) {
						console.log('拨打电话失败：', err);
					}
				});
			},
			initData:debounce(function(){
				uni.showLoading();
				const params = {
					page: this.page,
					limit: this.limit,
					status: this.orderStatus,
					name: this.lpgUserName
				};
				this.$API.orderList(params).then(res => {
					uni.hideLoading();
					this.mescroll.endSuccess(res.page.list.length);
					//设置列表数据
					if (res.page.currPage == 1) this.list = []; //如果是第一页需手动制空列表
					const currList = res.page.list;
					const arr = this.list.concat(currList); //追加新数据
					arr.map((item) => {
						if (item.status === 0) {
							const orderCancelTimer = 'orderCancelTimer' + item.id;
							this.allClearTimer.push({
								name: orderCancelTimer,
								id: item.id
							})
							item['countdown'] = ''
							this.startCountdown(item, orderCancelTimer);
						}
					})
				
					this.list = arr;
					console.log(this.list)
				}).catch(() => {
					//联网失败, 结束加载
					this.mescroll.endErr();
				});
			},200),
			startCountdown(item, orderCancelTimer) {
				// 当前时间
				let nowTime = new Date()
				// 获取创建订单30分钟后的时间,createTime:订单创建时间
				let endTime = new Date(item.createTime);
				endTime.setMinutes(endTime.getMinutes() + this.orderCountdown) // 结束时间，获取创建订单30分钟后的时间
				// 两个日期相差的时间戳，以毫秒为单位（1000ms = 1s）
				let distance = endTime - nowTime;
				// 结束时间大于现在的时间
				if (distance > 0) {
					this.$timerManager.setTimer(orderCancelTimer, 1000, () => {
						//console.log('计时器触发');
						if (distance > 0) {
							let minutes =
								Math.floor((((distance % (3600 * 24 * 1000)) / 1000) % 3600) / 60).toString()
								.padStart(2, "0");
							//获取秒数
							let seconds =
								Math.floor((((distance % (3600 * 24 * 1000)) / 1000) % 3600) % 60).toString()
								.padStart(2, "0");
							distance -= 1000;
							item.countdown = `${minutes}:${seconds}`;
							//console.log(item.countdown)
						}else{
							this.$timerManager.clearTimer(orderCancelTimer);
							item.countdown = '已过期';
							this.initData();
						}

					});
				}
			},
			//tabbar切换事件监听
			onTabbarClick(item) {

				//uni.setStorageSync('orderStatus',null)
				this.tabbarItem.selected = false;
				item.selected = true;
				this.tabbarItem = item;
				this.orderStatus = item.value;
				if (this.orderStatus === 2) {
					this.orderStatus = '1,2,3'
				}
				
				
				this.setUserOrderStatus(item)
				this.list = [];
				this.page = 1;
				this.mescroll.resetUpScroll() // 再刷新列表数据
			},
			// 下拉刷新
			downCallback() {
				//this.onInputChange();
				console.log('down')
			},
			/*上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10 */
			upCallback(page) {
				console.log('up')
				this.page = page.num;
				//联网加载数据
				this.initData();
			},
			// 主动触发下拉刷新
			triggerDownScroll() {
				this.mescroll.triggerDownScroll()
			},
			onInputChange() {
				this.initData();
			},
			onViewDetails(item) {
				uni.navigateTo({
					url: './orderDetail?orderItem=' + JSON.stringify(item)
				})
			},

		}
	}
</script>
<style>
	.uni-button-color {
		color:#E86748 !important;
	}
	
	page {
		background-color: #F9F9F9;
	}
</style>
<style lang="scss" scoped>
	.order-page {
		position: relative;
		background-image: linear-gradient(rgba(249, 195, 115, .3) 0%, #F9F9F9 100%);
		padding-bottom: 150rpx;
		//background:rgba(249, 195, 115, .6);
		.search-con {
			border-radius: 18rpx;
			padding: 20rpx 18rpx 0;

			.input-con {
				position: relative;
				width: 100%;
				border: 2rpx solid rgba(255, 154, 22, 1);
				height: 80rpx;
				line-height: 80rpx;
				padding-left: 18rpx;
				background: #ffffff;
				border-radius: 16rpx;
				font-size: 24rpx;

				.line {
					height: 40rpx;
					border: 2rpx solid rgba(255, 154, 22, 1);
					position: absolute;
					right: 115rpx;
				}

				text {
					font-size: 28rpx;
					font-family: PingFang-SC-Medium, PingFang-SC;
					font-weight: 500;
					color: #3E3E3E;
					line-height: 40rpx;
					position: absolute;
					right: 38rpx;
				}
			}

			/*修改提示文字的颜色*/
			input::-webkit-input-placeholder {
				color: #8B959F;
			}

			input:-moz-placeholder {
				color: #8B959F;
			}

			input::-moz-placeholder {
				color: #8B959F;
			}

			input:-ms-input-placeholder {
				color: #8B959F;
			}
		}

		.tabs-con {
			margin: 40rpx 40rpx 8rpx;
			width: 90%;

			.tab-item {
				font-size: 28rpx;
				font-weight: 500;
				color: #001F42;
				position: relative;
				padding-bottom: 14rpx;

				text {
					background: #FA4B4B;
					padding: 0 10rpx;
					border-radius: 50%;
					font-size: 24rpx;
					color: #ffffff;
					position: absolute;
					right: -20rpx;
					top: -14rpx;
				}

				.sele-bg {
					position: absolute;
					width: 90rpx;
					height: 24rpx;
					bottom: 5rpx;
				}
			}

			.selected {
				font-size: 30rpx;
				font-weight: 800;
				color: #333333;
			}

			//border-bottom: 6rpx solid #0084FF;
		}

		.p-list {
			margin: 20rpx 18rpx 0;

			.p-l-item {
				background: #FFFFFF;
				border-radius: 18rpx;
				padding: 15rpx 28rpx 20rpx;
				margin-bottom: 20rpx;
				position: relative;


				.title-con {
					border-bottom: 2rpx solid #F7F7F7;
					padding: 12rpx 0 23rpx;

					text:nth-child(1) {
						margin-left: 10rpx;
						font-family: PingFang-SC, PingFang-SC;
						font-weight: 500;
						font-size: 30rpx;
						color: #333333;
					}

					text:nth-child(2) {
						font-family: PingFang-SC, PingFang-SC;
						font-weight: 500;
						font-size: 28rpx;
						color: #E86748;
					}

					.order_stauts_complete {
						color: #6A6969 !important
					}

				}

				.p-content {
					margin: 25rpx 0 33rpx;

					.p-c-item {
						font-family: PingFang-SC, PingFang-SC;
						font-weight: 500;

						.goodInfo {
							width: 80%;

							.goodImg {
								width: 98rpx;
								height: 94rpx;
								background: #F5F5F5;
								border-radius: 14rpx;

								image {
									width: 100%;
									height: 100%;
								}
							}

							.standards {
								margin-left: 18rpx;

								view {
									font-family: PingFang-SC, PingFang-SC;
									font-weight: 400;
									font-size: 24rpx;
									color: #333333;
									margin-top: 10rpx;
								}

								view:nth-child(1) {

									font-weight: 500;
									font-size: 28rpx;

								}

							}
						}
					}

				}

				.p-btn {
					font-family: PingFang-SC, PingFang-SC;
					font-weight: 500;
					font-size: 28rpx;
					text-align: center;
					gap: 26rpx;

					.contactBtn {
						width: 166rpx;
						height: 58rpx;
						border-radius: 29rpx;
						border: 2rpx solid #D8D8D8;
						line-height: 58rpx;
						color: #3E3E3E;
					}

					.payBtn {
						width: 216rpx;
						height: 58rpx;
						background: linear-gradient(180deg, #F18858 0%, #E86547 100%);
						border-radius: 29rpx;
						color: #FFFFFF;
						line-height: 58rpx;
					}

					.sureBtn {
						border: 2rpx solid transparent;
						line-height: 80rpx;
						width: 316rpx;
						height: 80rpx;
						line-height: 80rpx;
						background: linear-gradient(180deg, #F18858 0%, #E86547 100%);
						border-radius: 16rpx;
						color: #FFFFFF;
					}

					
				}
			}
		}

		.p-price {
			margin: 24rpx 0;

			view {
				font-family: PingFang-SC, PingFang-SC;
				font-weight: 400;
				font-size: 28rpx;
				color: #000000;
			}

			view:nth-child(2) {
				font-weight: 600;
			}

			.payAmount {
				.txt_0 {
					font-weight: 600;
					font-size: 36rpx;
					color: #000000;
				}
				.txt_1 {
					margin-left: 10rpx;
					font-size: 26rpx;
					color: #6A6969;
					font-weight: 500;
				}
				text{
					font-weight: 500;
					font-size: 28rpx;
					color: #6A6969;
				}
			}
		}

	}
</style>